package com.wizz.trade.trading.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wizz.trade.common.PageVo;
import com.wizz.trade.information.mapper.*;
import com.wizz.trade.trading.dto.SpotSettlementPriceDto;
import com.wizz.trade.trading.dto.page.PositionPageDto;
import com.wizz.trade.trading.entity.ImportCost;
import com.wizz.trade.trading.entity.Position;
import com.wizz.trade.trading.mapper.ImportCostMapper;
import com.wizz.trade.trading.mapper.PositionMapper;
import com.wizz.trade.trading.service.PositionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wizz.trade.trading.vo.GetSPriceVo;
import com.wizz.trade.trading.vo.PositionVo;
import com.wizz.trade.util.PageUtil;
import org.apache.commons.collections4.Get;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 持仓表 服务实现类
 * </p>
 *
 * @author fyftless
 * @since 2023-04-23 04:37:04
 */
@Service
public class PositionServiceImpl extends ServiceImpl<PositionMapper, Position> implements PositionService {

    @Resource
    private PositionMapper positionMapper;

    @Resource
    private CompanyMapper companyMapper;

    @Resource
    private CompanydeptMapper companydeptMapper;

    @Resource
    private VarietyMapper varietyMapper;

    @Resource
    private GradeMapper gradeMapper;

    @Resource
    private TrademarkMapper trademarkMapper;

    @Resource
    private CurrencyMapper currencyMapper;

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private ImportCostMapper importCostMapper;

    @Override
    public void addPosition(Position position) {
        positionMapper.insert(position);
    }

    @Override
    public void updatePosition(Position position) {
        positionMapper.updateById(position);
    }

    @Override
    public void deletePosition(Integer id) {
        positionMapper.deleteById(id);
    }

    @Override
    public PageVo<PositionVo> getPage(PositionPageDto positionPageDto) {
        LambdaQueryWrapper<Position> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Objects.nonNull(positionPageDto.getDate()), Position::getDate, positionPageDto.getDate());
        queryWrapper.eq(Objects.nonNull(positionPageDto.getLedger()), Position::getLedger, positionPageDto.getLedger());
        queryWrapper.eq(Objects.nonNull(positionPageDto.getOurdept()), Position::getOurDept, positionPageDto.getOurdept());
        queryWrapper.eq(Objects.nonNull(positionPageDto.getCompany()), Position::getCompany, positionPageDto.getCompany());
        queryWrapper.eq(Objects.nonNull(positionPageDto.getCompanyDept()), Position::getCompanyDept, positionPageDto.getCompanyDept());
        queryWrapper.eq(Objects.nonNull(positionPageDto.getVarietyId()), Position::getVariety, positionPageDto.getVarietyId());
        queryWrapper.eq(Objects.nonNull(positionPageDto.getGrade()), Position::getGrade, positionPageDto.getGrade());
        queryWrapper.eq(Objects.nonNull(positionPageDto.getTrademark()), Position::getTrademark, positionPageDto.getTrademark());
        queryWrapper.eq(Objects.nonNull(positionPageDto.getPattern()), Position::getPattern, positionPageDto.getPattern());
        queryWrapper.eq(Objects.nonNull(positionPageDto.getDeliver()), Position::getDeliver, positionPageDto.getDeliver());
        queryWrapper.eq(Objects.nonNull(positionPageDto.getOrderId()), Position::getOrderId, positionPageDto.getOrderId());
        Page<Position> page = positionMapper.selectPage(PageUtil.initPage(positionPageDto), queryWrapper);
        List<Position> records = page.getRecords();

        List<PositionVo> list = records.stream().map((item) ->{
            PositionVo positionVo = new PositionVo();
            BeanUtils.copyProperties(item, positionVo);
            positionVo.setLedger(companyMapper.selectById(item.getLedger()).getShortname());
            positionVo.setOurdept(companydeptMapper.selectById(item.getOurDept()).getName());
            positionVo.setCompany(companyMapper.selectById(item.getCompany()).getShortname());
            positionVo.setVariety(varietyMapper.selectById(item.getVariety()).getName());
            positionVo.setGrade(gradeMapper.selectById(item.getGrade()).getName());
            positionVo.setTrademark(trademarkMapper.selectById(item.getTrademark()).getName());
            positionVo.setOrderId(ordersMapper.selectById(item.getOrderId()).getMode());
            positionVo.setCurrency(currencyMapper.selectById(item.getCurrency()).getName());
            ImportCost importCost = importCostMapper.getImportCostIdByPositionId(item.getId());
            positionVo.setExrate(importCost.getExrate());
            positionVo.setCostprice(importCost.getCostprice());
            positionVo.setSettleprice(importCost.getSettleprice());
            positionVo.setReffpl(importCost.getReffpl());
            positionVo.setRefCurrency(currencyMapper.selectById(importCost.getCurrency()).getName());
            return positionVo;
        }).collect(Collectors.toList());
        return new PageVo<>(page.getPages(), page.getTotal(), list);
    }

    @Override
    public List<Position> getAll() {
        return positionMapper.selectList(null);
    }

    @Override
    public List<GetSPriceVo> getSettlementPrice() {
        List<Integer> settlementPrice = positionMapper.getSettlementPrice();
        List<Integer> allIds = positionMapper.getAllIds();
        int j = allIds.size()-1;
        List<GetSPriceVo> getSPriceVos = new ArrayList<>();
        for(int i = settlementPrice.size()-1; i>=0;i--){
            GetSPriceVo getSPriceVo =  new GetSPriceVo();
            Integer realId = settlementPrice.get(i);
            StringBuilder ids = new StringBuilder();
            for(; j>=0; j--){
                ids.append(allIds.get(j));
                if(allIds.get(j).equals(realId)){
                    j--;
                    break;
                }
                ids.append(",");
            }
            getSPriceVo.setGroupIds(ids.toString());
            Position item = positionMapper.selectById(realId);
            PositionVo positionVo = new PositionVo();
            BeanUtils.copyProperties(item, positionVo);
            positionVo.setLedger(companyMapper.selectById(item.getLedger()).getShortname());
            positionVo.setOurdept(companydeptMapper.selectById(item.getOurDept()).getName());
            positionVo.setCompany(companyMapper.selectById(item.getCompany()).getShortname());
            positionVo.setVariety(varietyMapper.selectById(item.getVariety()).getName());
            positionVo.setGrade(gradeMapper.selectById(item.getGrade()).getName());
            positionVo.setTrademark(trademarkMapper.selectById(item.getTrademark()).getName());
            positionVo.setOrderId(ordersMapper.selectById(item.getOrderId()).getMode());
            positionVo.setCurrency(currencyMapper.selectById(item.getCurrency()).getName());
            getSPriceVo.setPositionVo(positionVo);
            getSPriceVos.add(getSPriceVo);
        }
        return getSPriceVos;
    }

    @Override
    public void setSettlementPrice(List<SpotSettlementPriceDto> dtos) {
        for (SpotSettlementPriceDto dto : dtos) {
            Position position = positionMapper.selectById(dto.getId());
            position.setSprice(dto.getSprice());
            ImportCost importCost = importCostMapper.getImportCostIdByPositionId(position.getId());
            importCost.setSettleprice(dto.getSettleprice());
            position.setFpl((position.getSprice().subtract(position.getCprice())).
                    multiply(position.getOi()));
            position.setStorageCapital(position.getCprice().multiply(position.getOi()));
            positionMapper.updateById(position);
            //如果进出口成本不为空，则计算浮盈
            if(Objects.nonNull(importCost.getCostprice())){
                importCost.setReffpl((importCost.getSettleprice().subtract(importCost.getCostprice())).
                        multiply(position.getOi()));
            }
            importCostMapper.updateById(importCost);
        }
    }

}
